package com.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/index")
public class IndexController {

    @RequestMapping("/hello/{id}")
    @SentinelResource(value = "testBlock", blockHandler = "blockHandlerException", fallback = "fallback", fallbackClass = IndexController.class, blockHandlerClass = IndexController.class)
    public String index(@PathVariable("id") int id){
        if(id <= 0) {
            throw new NullPointerException("参数错误");
        }
        return "首页";
    }

    public static String blockHandlerException(int id, BlockException e){
        e.printStackTrace();
        return "被限流了";
    }


    public static String fallback(int id, Throwable e){
        e.printStackTrace();
        return "被降级了";
    }

    @PostConstruct
    public void loadFlowRule(){
        initFlowRules();
    }

    public static void initFlowRules() {
        List<FlowRule> flowRules = new ArrayList();
        FlowRule flowRule = new FlowRule();
        flowRule.setCount(1);
        flowRule.setResource("testBlock");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRules.add(flowRule);
        FlowRuleManager.loadRules(flowRules);
    }
}
